package com.jhc.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jhc.bo.UserSaveDetails;
import com.jhc.dto.CmsLogin;
import com.jhc.dto.CmsUpdatePasswordDto;
import com.jhc.dto.CmsUserPermissionAdd;
import com.jhc.dto.CmsUserRoleAdd;
import com.jhc.entity.CmsUser;
import com.jhc.entity.RedisUserInfo;
import com.jhc.entity.UserAuthData;
import com.jhc.service.IBacCollegeService;
import com.jhc.service.ICmsUserService;
import com.jhc.service.RedisService;
import com.jhc.utils.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author zhengyue
 * @since 2020-03-13
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户 用户管理")
public class CmsUserController {

    @Autowired
    private ICmsUserService iCmsUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IBacCollegeService iBacCollegeService;
    @Autowired
    private UserSaveDetails userSaveDetails;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @PostMapping("/login")
    @ApiOperation("用户登陆")
    public CommonResult login(@RequestBody @Validated CmsLogin cmsLogin) {
        RedisUserInfo redisUserInfo = iCmsUserService.login(cmsLogin.getNumber(), cmsLogin.getPassword());
        if (redisUserInfo.getToken() == null) {
            return CommonResult.validateFailed("账号密码错误");
        }
        redisUserInfo.setPermissionList(null);
        return CommonResult.success(redisUserInfo);
    }

    @ApiOperation("用户登出")
    @DeleteMapping("/logout/{staffNumber}")
    public CommonResult logout() {
        redisService.remove(userSaveDetails.getCmsUser().getNumber());
        return CommonResult.success("成功");
    }

    @ApiOperation("查询用户权限user:permission:get")
    @GetMapping("/{number}")
    @PreAuthorize("hasAuthority('user:permission:get')")
    public CommonResult getPermission(@PathVariable String number) {
        return CommonResult.success(iCmsUserService.getPermissionList(number), "查询成功");
    }

    @ApiOperation("更新用户权限user:permission:update")
    @PutMapping("/add/permission")
    @PreAuthorize("hasAuthority('user:permission:update')")
    public CommonResult addPermission(@Validated @RequestBody CmsUserPermissionAdd cmsUserPermissionAdd) {
        // 去重
        cmsUserPermissionAdd.setAuthList(cmsUserPermissionAdd.getAuthList().stream().distinct().collect(Collectors.toList()));
        if (iCmsUserService.userAddPermission(cmsUserPermissionAdd)) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.success("添加失败");
    }

    @ApiOperation("添加用户角色user:role:add")
    @PostMapping("/role")
    @PreAuthorize("hasAuthority('user:role:add')")
    public CommonResult addRole(@Validated @RequestBody CmsUserRoleAdd cmsUserRoleAdd) {
        if (iCmsUserService.userAddRole(cmsUserRoleAdd)) {
            return CommonResult.success("添加成功");
        }
        return CommonResult.failed("用户不存在或者角色不存在");

    }

    @ApiOperation("删除用户角色user:role:delete")
    @DeleteMapping("/role")
    @PreAuthorize("hasAuthority('user:role:delete')")
    public CommonResult removeRole(@Validated @RequestBody CmsUserRoleAdd cmsUserRoleAdd) {
        if (iCmsUserService.userRemoveRole(cmsUserRoleAdd)) {
            return CommonResult.success("删除成功");
        }
        return CommonResult.failed("删除失败");
    }

    @ApiOperation("修改用户密码")
    @PatchMapping("/password")
    public CommonResult updatePassword(@Validated @RequestBody CmsUpdatePasswordDto cmsUpdatePasswordDto) {
        if (iCmsUserService.getOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber, cmsUpdatePasswordDto.getNumber())) == null) {
            return CommonResult.failed("用户不存在");
        }
        if (iCmsUserService.updatePassword(cmsUpdatePasswordDto)) {
            return CommonResult.success("修改成功，请重新登陆");
        }
        return CommonResult.failed("修改失败");
    }

    @ApiOperation("根据用户姓名模糊查询")
    @GetMapping("/userListByLikeName/{name}")
    public CommonResult getUserListByLikeName(@PathVariable(name = "name") String name) {
        List<CmsUser> users = iCmsUserService.getUserListByLikeName(name);
        if(users.size() > 0) {
            //构造返回对象
            List<Map<String, Object>> resultList = new ArrayList<>();
            users.stream().forEach(teacher -> {
                Map<String, Object> map = new HashMap<>();
                map.put("userNumber", teacher.getNumber());
                map.put("userName", teacher.getName());
                resultList.add(map);
            });
            return CommonResult.success(resultList);
        } else {
            return CommonResult.failed("没有匹配的用户列表");
        }


    }

}
